package com.boco.pciv.service.sys.impl;

import cn.hutool.core.convert.Convert;
import com.boco.pciv.core.entity.BizTree;
import com.boco.pciv.core.exception.PcivException;
import com.boco.pciv.core.service.PcivBaseServiceImpl;
import com.boco.pciv.core.util.SearchUtil;
import com.boco.pciv.core.entity.Constants;
import com.boco.pciv.core.entity.SearchCriteria;
import com.boco.pciv.core.entity.SelectItem;
import com.boco.pciv.entity.sys.DeptInfo;
import com.boco.pciv.mapper.sys.IDeptMapper;
import com.boco.pciv.service.sys.IDeptService;
import cn.hutool.core.util.StrUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.stereotype.Service;

import java.util.*;
import java.util.stream.Collectors;

/**
 * Created by CC on 2017/1/18.
 */
@Service
public class DeptServiceImpl extends PcivBaseServiceImpl<IDeptMapper,DeptInfo,String> implements IDeptService {
    @Autowired
    IDeptService self;

    @Override
    @Cacheable("dept")
    public List<DeptInfo> getAll() {
        SearchCriteria cond = new SearchCriteria();
        cond.setIsPage(false);
        List<DeptInfo> list = mapper.queryList(cond.getQueryMap());
        if (list!=null) {
            for (DeptInfo item : list) {
                final String pid = item.getParentId();
                if (pid.equals(Constants.DeptParentID)) {
                    item.setParentName(Constants.DeptParentName);
                } else {
                    //查找父节点
                    List<DeptInfo> list1 = list.stream().filter(s -> s.getId().equals(pid))
                            .collect(Collectors.toList());
                    if (list1 != null && list1.size() > 0) {
                        item.setParentName(list1.get(0).getName());
                    }
                }
            }
        }
        return  list;
    }

    @Override
    @Cacheable(value = "dept",key = "#id")
    public DeptInfo getOne(String id) {
        return super.getOne(id);
    }

    @Override
    public BizTree getDeptTreeByParent(String parentId) {
        BizTree tree = new BizTree();

        if(StrUtil.isBlank(parentId) || Constants.DeptParentID.equals(parentId)){
            tree.setId(Constants.DeptParentID);
            tree.setName(Constants.DeptParentName);
        }
        else{
            DeptInfo root = self.getOne(parentId);
            if(root!=null) {
                tree.setId(root.getId());
                tree.setName(root.getName());
            }
        }

        List<DeptInfo> list = self.getAll();
        tree.setChildren(AddChildResource(tree,list));

        return tree;
    }

    @Override
    public List<SelectItem> getDeptTreeByParent4Select(String parentId) {
        BizTree tree = getDeptTreeByParent(parentId);
        String deptItemType = "DeptTreeList";
        return SearchUtil.EasyTree2TreeList(tree,deptItemType);
    }

    private  List<BizTree> AddChildResource(final BizTree curNode, List<DeptInfo> AllSource) {
        List<DeptInfo> childLst = AllSource.stream()
                .filter(s -> s.getParentId().equals(curNode.getId()))
                .collect(Collectors.toList());

        List<BizTree> childResourceTree = new ArrayList<BizTree>();
        if (childLst!= null) {
            //排序
            childLst=childLst.stream().sorted(new Comparator<DeptInfo>() {
                @Override
                public int compare(DeptInfo o1, DeptInfo o2) {
                    Integer i1 = Convert.toInt(o1.getRank(),0);
                    Integer i2 =  Convert.toInt(o2.getRank(),0);
                    return i1>i2 ? 1 : 0;
                }
            }).collect(Collectors.toList());

            for (DeptInfo item : childLst) {
                BizTree cur = new BizTree();
                cur.setId(item.getId());
                cur.setName(item.getName());
                cur.setChildren(AddChildResource(cur, AllSource));
                childResourceTree.add(cur);
            }
        }
        return childResourceTree;
    }

    @Override
    @CacheEvict(value = "dept",allEntries=true)
    public void add(DeptInfo data) {
        //检查id是否重复
        DeptInfo info = mapper.queryOne(data.getId());
        if (info!=null){
            throw new PcivException("部门id已存在");
        }
        //设置级别
        data.setState(1);
        if (data.getType()==null){
            data.setType(0);
        }
        data.setLevelId(getLevelId(data));
        mapper.insert(data);
    }

    @Override
    @CacheEvict(value = "dept",allEntries=true)
    public Integer edit(DeptInfo data) {
        //设置级别
        data.setLevelId(getLevelId(data));
        if (data.getType()==null){
            data.setType(0);
        }
        return  mapper.update(data);
    }

    private Integer getLevelId(DeptInfo data){
        //设置级别
        String pid = data.getParentId();
        if (StrUtil.isBlank(pid)) {
            return 1;
        }
        else{
            DeptInfo p = getOne(pid);
            if (p!=null){
                Integer plevelId= p.getLevelId();
                if(plevelId!= null)
                    return  p.getLevelId()+1;
            }
        }
        return  1;
    }

    @Override
    @CacheEvict(value = "dept",allEntries=true)
    public void delete(String deptid) {
        mapper.delete(deptid);
    }
}
